import 'dart:developer';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:huxiaodui/config.dart';
import 'package:huxiaodui/main.dart';
import 'package:huxiaodui/utils/tools/notification_tool.dart';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:path_provider/path_provider.dart';

class AndroidUpdate {
  static double percent = 0;
  static Dio? dio;
  static int receivedBytes = 0;
  static int totalBytes = 0;
  static CancelToken cancelToken = CancelToken();

  static String getFileName(String url) {
    List<String> lstStr = url.split('/');
    return lstStr.last;
  }

  static String getVersion(String url) {
    String name = getFileName(url);
    return name.split('_')[1];
  }

  static Future<String> getApkPath(String v) async {
    Directory appDocumentsDir = await getApplicationDocumentsDirectory();
    return '${appDocumentsDir.path}/apk/app_${v}_release.apk';
  }

  static Future<String> getDownPath() async {
    Directory appDocumentsDir = await getApplicationDocumentsDirectory();
    return '${appDocumentsDir.path}/apk/down-app-release.apk';
  }

  static Future<File?> getApk(String v) async {
    File f = File(await getApkPath(v));
    if (f.existsSync()) {
      return f;
    }
    return null;
  }

  static Future<void> delApk() async {
    Directory appDocumentsDir = await getApplicationDocumentsDirectory();
    String path = '${appDocumentsDir.path}/apk/';
    Directory directory = Directory(path);
    if (directory.existsSync()) {
      directory.deleteSync(recursive: true);
    }
  }

  static Future<void> installApk(String v) async {
    await InstallPlugin.installApk(await getApkPath(v));
  }

  /// 下载安卓更新包
  static Future<void> download({
    required String version,
    required String url,
    Widget? content,
  }) async {
    if (dio == null) {
      dio = Dio();
    } else {
      EasyLoading.showInfo("正在下载中");
      return;
    }
    String filePathDown = await getDownPath();
    String filePath = await getApkPath(version);

    File file = File(filePathDown);
    try {
      dio = Dio();
      cancelToken = CancelToken();
      Response response = await dio!.download(
        url,
        filePathDown,
        cancelToken: cancelToken,
        onReceiveProgress: (int count, int total) async {
          if (cancelToken.isCancelled) {
            return;
          }
          receivedBytes = count;
          totalBytes = total;

          double receivedMB = receivedBytes / (1024 * 1024); // 转换为MB
          double totalMB = totalBytes / (1024 * 1024); // 转换为MB
          if (count < total) {
            await NotificationTool().downApk("应用更新",
                "进度：${receivedMB.toStringAsFixed(1)}MB/${totalMB.toStringAsFixed(1)}MB");
          }
        },
      );
      print("下载完成 ${response.data.statusCode}");
      if (response.data.statusCode == 200) {
        file.renameSync(filePath);
        NotificationTool.notificationsPlugin.cancel(4);
        await NotificationTool().downApk(
          "应用更新",
          "应用更新完成(点击安装)",
          onDidReceiveNotificationResponse: (res) {
            AndroidUpdate.installApk(version);
          },
        );

        _showInstallDialog(version, url, content);

      }
    } catch (e) {
      log(e.toString());
    }

    dio = null;
  }

  static void _showInstallDialog(String version, String url, Widget? content) {
    showDialog(
      context: navigatorKey.currentState!.context,
      builder: (context) => AlertDialog(
        title: const Text("检测到新版本是否需要安装?"),
        content: content,
        actions: [
          TextButton(
            child: const Text('重新下载'),
            onPressed: () async {
              Navigator.pop(context, true);
              await AndroidUpdate.delApk();
              AndroidUpdate.download(
                version: version,
                url: url,
                content: content,
              );
            },
          ),
          TextButton(
            child: const Text('立即安装'),
            onPressed: () async {
              Navigator.pop(context, true);
              await AndroidUpdate.installApk(version);
            },
          ),
        ],
      ),
    );
  }

  static show({
    required String version,
    required String url,
    Widget? content,
  }) async {
    if (!Platform.isAndroid) {
      return;
    }

    if (AndroidUpdate.dio != null) {
      showDialog(
        context: navigatorKey.currentState!.context,
        builder: (context) => AlertDialog(
          title: const Text("正在下载中..."),
          content: content,
          actions: [
            TextButton(
              child: const Text('取消更新'),
              onPressed: () async {
                AndroidUpdate.cancel();
                Navigator.pop(context, true);
              },
            ),
            TextButton(
              child: const Text('继续'),
              onPressed: () async {
                Navigator.pop(context, true);
              },
            ),
          ],
        ),
      );
      return;
    }
    bool isApk = (await AndroidUpdate.getApk(version)) != null;
    if (isApk) {
      _showInstallDialog(version, url, content);
      return;
    }
    showDialog(
      context: navigatorKey.currentState!.context,
      builder: (context) => AlertDialog(
        title: Text("发现新版本 $version"),
        content: content,
        actions: [
          TextButton(
            child: const Text('立即下载'),
            onPressed: () async {
              Navigator.pop(context, true);
              AndroidUpdate.download(
                version: version,
                url: url,
                content:content,
              );
            },
          ),
        ],
      ),
    );
  }

  static void cancel() {
    cancelToken.cancel();
    NotificationTool.notificationsPlugin.cancel(4);
  }
}
